package com.wan.nettyproject;

import android.util.Log;

import com.google.gson.Gson;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;


/**
 * Created by itsxzx008 on 2016/5/4.
 */
public class SocketThread extends Thread {
    private Bootstrap clientBootstrap = null;
    private ChannelFuture future = null;
    private EventLoopGroup workerGroup = new NioEventLoopGroup();
    private ChannelInboundHandlerAdapter handlerAdapter;
    private String strHost = null;
    private int nPort = 0;

    public SocketThread(String strHost, int nPort, ChannelInboundHandlerAdapter handler) {
        this.strHost = strHost;
        this.nPort = nPort;
        this.handlerAdapter=handler;
    }

    @Override
    public void run() {
        doConnect();
    }


    public boolean doConnect() {
        boolean isSuccess;
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class);
        b.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
                pipeline.addLast("handler", new MsgServerHandler());
            }
        });

        b.option(ChannelOption.SO_KEEPALIVE, true);

        try {
            future=b.connect(UrlConfig.IP, UrlConfig.PORT).sync();
            isSuccess=true;
        } catch (InterruptedException e) {
            e.printStackTrace();
            Log.e("test", "连接服务器失败:" + e.getCause().toString());
            isSuccess=false;
        }
        return isSuccess;
    }


    /**
     * @return
     */
    public boolean sendRequest(Object object) {

        if (null != object && null != future.channel()) {
            /**底层的状态要提前判断，netty抛出的异常上层catch不到*/
            Channel currentChannel = future.channel();
            boolean isW = currentChannel.isWritable();
            if (!(isW)) {
                throw new RuntimeException("发送失败，连接关闭了");
            }
            String str = new Gson().toJson(object);
           /* Cha buffer = ChannelBuffers.buffer(str.length());
            buffer.writeBytes(str.getBytes());*/
            future.channel().writeAndFlush(str);
            return true;
        } else {
            return false;
        }
    }
}
